<template>
  <div class="z-echarts w-full h-full"
       ref="z-echarts"></div>
</template>

<script>
import * as Echarts from 'echarts'
import { debounce } from 'lodash'
export default {
  name: 'ZEcharts',
  props: {
    options: {
      type: Object,
      required: true
    },
  },
  data () {
    return {
      echartRef: null,
      observer: null
    }
  },
  computed: {
    realOptions () {
      return Object.assign(this.options, {
        grid: {
          containLabel: true,
          left: 0,
          top: 30,
          right: 0,
          bottom: 20
        }
      })
    }
  },
  watch: {
    realOptions: {
      handler (options) {
        if (this.echartRef) {
          this.echartRef.setOption(options)
        }
      },
      deep: true
    }
  },
  mounted () {
    this.initChart()
    this.observer = new ResizeObserver(this.resizeHandler);
  },
  activated () {
    if (this.echartRef) {
      this.echartRef.resize()
    }
  },
  beforeDestroy () {
    this.observer.disconnect();
  },
  methods: {
    initChart () {
      this.$nextTick(() => {
        const el = this.$refs['z-echarts']
        if (el) {
          this.echartRef = Echarts.init(el)
          this.echartRef.setOption(this.realOptions || {})
          this.observer.observe(el);
        }
      })
    },
    resizeHandler: debounce(function () {
      if (this.echartRef) {
        this.echartRef.resize()
      }
    }, 100)

  }
}
</script>